import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import GatherInterfaceBtn from '@main/entities/service/admin/gather/gather-interface-btn.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
@Injectable()
export class GatherInterfaceBtnService {
  constructor(
    @InjectRepository(GatherInterfaceBtn)
    private interfaceBtnRepository: Repository<GatherInterfaceBtn>
  ) {}

  async list() {
    return await this.interfaceBtnRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { btnName, btnCode } = entity;

    return await this.interfaceBtnRepository.findAndCount({
      where: {
        btnName: Like(`%${btnName}%`),
        btnCode: Like(`%${btnCode}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user) {
    await this.interfaceBtnRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
  }

  /**
   * 更新
   */
  async update(data, user) {
    const { id, remark, btnName, interfaceJson } = data;

    await this.interfaceBtnRepository.update(
      { id },
      {
        btnName,
        interfaceJson,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
  }

  /**
   * 删除
   */
  async delete(idList) {
    await this.interfaceBtnRepository.delete(idList);
  }

  async isExistKey(data) {
    const { btnCode } = data;

    const result = await this.interfaceBtnRepository.findOne({
      where: { btnCode },
    });

    if (result) {
      throw new ApiException(10041);
    }
  }
}
